<template>
   <div id="OrderConfirm">
      <van-overlay :show="overlayVisable" z-index="2" @click="test">
         <div class="wrapper">
            <van-loading size="24px">
               <span id="loading">数据加载中...</span>
            </van-loading>
         </div>
      </van-overlay>
      <div v-if="payVisable">

         <div class="title">
            <van-nav-bar id="banner" @click-left="onClickLeft">
               <template #title>
                  <div style="color: grey;">
                     提交订单
                  </div>
               </template>
               <template #left>
                  <div style="color:white">
                     <van-icon name="arrow-left" color="white" />
                     返回
                  </div>
               </template>
            </van-nav-bar>
         </div>
         <van-cell style="border-radius: 10px;width: 96%;margin-left: 2%;margin-top:10px ;"
            @click="showAddressVisable = ! showAddressVisable">
            <template #title>
               <div style="font-weight: 550;font-size: 14px;">
                  <span>送餐地址</span>
               </div>
            </template>
            <template>
               <div style="float: right;color: gray;font-size: 12px;">
                  <van-icon name="location-o" />切换地址
               </div>
            </template>
         </van-cell>
         <div id="box01">
            <span style="font-size: 18px;">{{selectedAddress.address}}</span>
            <div style="display: flex;font-size: 12px;color: gray;margin-top: 8px;">
               <span>{{selectedAddress.customerName}}</span>
               <span style="margin-left: 5px;">同学</span>
               <span style="margin-left: 5px;">{{selectedAddress.tel}}</span>
            </div>
            <div style="height: 8px;"></div>
            <span style="font-size: 10px;color:orange;">为了减少接触, 降低风险, 推荐使用无接触配送</span>
            <div style="margin-top: 20px;display: flex;">
               <span style="font-size: 10px;font-weight: 600;">立即送出</span>
               <span style="font-size: 10px;color: orange;margin-left: 170px;">大约40分钟后送达</span>
            </div>
         </div>

         <!-- 支付宝支付 普通支付 -->
         <van-cell style="border-radius: 10px;width: 95%;margin-left: 2%;margin-top:10px ;">
            <template #title>
               <div style="font-weight: 550;font-size: 14px;">
                  <span>支付方式</span>
               </div>
            </template>
            <template>
               <div style="float: right;color: gray;font-size: 12px;">
                  <van-icon name="peer-pay" />普通支付
               </div>
            </template>
         </van-cell>

         <div id="box02">
            <van-cell-group inset style="">
               <van-cell style="border-radius: 10px;width: 95%;margin-left: 2%;margin-top:10px ;">
                  <template #title>
                     <div style="font-weight: 550;font-size: 14px;">
                        <span>{{order.shopName}}</span>
                     </div>
                  </template>
                  <template>
                     <div style="float: right;font-size: 12px;">
                        <van-tag type="warning">商家自配</van-tag>
                     </div>
                  </template>
               </van-cell>
            </van-cell-group>
            <div id="food">
               <van-card v-for="(food,index) in order.foodList" :key="index" :origin-price="food.oldPrice"
                  style="margin-top: 5px;width: 95%;height: 100px;" :num="food.num">
                  <template #thumb>
                     <img :src="food.icon" style="width: 90%;height: 85%;">
                  </template>
                  <template #title>
                     <span style="font-weight: 700;font-size: 14px;"> {{ food.name }}</span>
                  </template>
                  <template #desc>
                     <div style="height: 10px;"></div>
                     <div style="color: gray;">
                        <p>{{ food.description }}</p>
                     </div>
                  </template>
                  <template #price>
                     <span style="color: red;"> ¥{{ food.price * food.num }}</span>
                  </template>

               </van-card>

            </div>
            <div style="height: 20px;"> </div>
         </div>
         <van-cell style="border-radius: 10px;width: 95%;margin-left: 2%;margin-top:5px ;">
            <template #title>
               <div style="font-weight: 550;font-size: 14px;">
                  <span>合计</span>
               </div>
            </template>
            <template>
               <div style="float: right;margin-right: 5px;font-size: 15px;color: red;font-weight: 600;">
                  <span>¥{{(order.totalMoney*1.0).toFixed(2)}}</span>
               </div>
            </template>
         </van-cell>
         <div>
            <van-button class="myButton" round block type="warning" native-type="submit" @click="makeOrder">
               提交
            </van-button>
         </div>
         <div style="height: 20px;"></div>
         <van-action-sheet v-model="showAddressVisable" :actions="actions" @select="onSelect" cancel-text="取消" />
      </div>

      <div v-else>
         <div class="title">
            <van-nav-bar id="banner" @click-left="onClickLeft">
               <template #title>
                  <div style="color: grey;">
                     支付订单
                  </div>
               </template>
            </van-nav-bar>
         </div>

         <div style="margin-top: 25%;">
            <div style="display: flex;margin-left: 30%;">
               <p style="font-size:12px ;color: gray;margin-top: 4px;">支付剩余时间</p>
               <van-count-down @finish="finish" :time="time" format="mm 分 ss 秒"
                  style="color: grey;font-size: 10px;margin-left: 2%;" />
            </div>
            <p style="margin-top:2%;text-align: center;"> <span style="font-size: 15px;">¥</span> <span
                  style="font-size: 40px;"> {{order.totalMoney}}</span></p>
            <p style="text-align: center;color: grey;font-size: 14px;margin-top: 2%;">{{order.shopName}}</p>
            <van-cell style="width: 95%;border-radius: 10px;margin-left: 3%;margin-top: 15%;"
               @click="showPayTypeVisable = !showPayTypeVisable">
               <template #title>
                  支付方式
               </template>
               <template>
                  {{payType}}
                  <van-icon name="arrow" />
               </template>

            </van-cell>
            <div style="display: flex;margin-top: 2%;">
               <van-button class="myButton" style="width: 50%;margin-left: 5%;" round block type="warning"
                  native-type="submit" @click="showInputPayVisible">
                  支付
               </van-button>
               <van-button class="myButton" style="width: 50%;background-color: white;color: black;" round block
                  type="warning" native-type="submit" @click="onCancel">
                  取消
               </van-button>
            </div>
         </div>
         <van-popup class="inputPassword" :overlay="false" style="margin-left: 0px;margin-top: -80px;"
            :close-on-click-overlay="false" v-model="inputPassWordVisible">
            <p style="text-align: center;margin-top: 10%;font-weight: 500;letter-spacing: 1px;">请输入支付密码</p>
            <p style="text-align: center;margin-top: 5%;font-size: 14px;">金额: {{(order.totalMoney*1.0).toFixed(2)}}元</p>
            <van-password-input style="margin-top: 5%;" :value="password" :focused="showKeyboard"
               @focus="showKeyboard = true" />
         </van-popup>
         <van-number-keyboard theme="custom" close-button-text="完成" v-model="password" :show="showKeyboard"
            @blur="checkPassword" />
         <van-action-sheet v-model="showPayTypeVisable" :actions="option" cancel-text="取消" @select="onSelectPayType" />
      </div>
   </div>


</template>
<script>
   import request from '@/utils/request';
   import {
      Dialog,
      Toast
   } from 'vant'
   import {
      mapActions
   } from 'vuex';
   export default {
      name: '',
      data() {
         return {
            time: 0,
            overlayVisable: true,
            order: {},
            inputPassWordVisible: false,
            showAddressVisable: false,
            selectedAddress: {},
            password: '',
            showKeyboard: false,
            addressList: [],
            actions: [

            ],
            url: {
               order: "/schoolOrder/app/order/order"
            },
            option: [{
               name: '余额支付'
            }, {
               name: '微信支付'
            }, {
               name: '支付宝支付'
            }],
            payType: '余额支付',
            showPayTypeVisable: false,
            payVisable: true,
            customerInfo: {},
         }
      },
      computed: {

      },
      methods: {
         ...mapActions("customer", [
            "updateCustomerInfo",
         ]),
         onClickLeft() {
            this.$router.go(-1)
            console.log();
         },
         onSelect(item) {
            this.selectedAddress = item;
            this.showAddressVisable = false;
         },

         /**
          *   确认提交订单
          */
         makeOrder() {
            Dialog.confirm({
                  title: '提交订单',
                  message: '确定提交订单了吗？',
               })
               .then(() => {
                  this.order.status = 2;
                  this.order.customerId = this.customerInfo.id;
                  this.order.createBy = this.order.createBy;
                  this.order.username = this.customerInfo.username; //下单用户名
                  this.order.name = this.selectedAddress.customerName; //收货姓名
                  this.order.tel = this.selectedAddress.tel; //电话
                  this.order.address = this.selectedAddress.address;
                  //提交订单后直接插入数据库 状态设置为未支付
                  request.post(this.url.order, 
                     this.order
                  ).then(res => {
                     this.order.id = res.data.data
                  })
                  this.payVisable = false;
                  sessionStorage.setItem(this.customerInfo.username + this.order
                     .shopName + "waitPay", false)
               })
               .catch(() => {

               });

         },

         /**
          * 倒计时结束 取消订单 跳转到订单界面
          */
         finish() {
            // console.log("倒计时结束")
            Dialog.alert({
               title: '提示',
               message: '未在15分钟内支付订单',
            }).then(() => {
               this.order.status = 8;
               this.upDateStatusById(this.order);
               sessionStorage.setItem('curActive', 1);
               this.$router.push("/manager/order")
            });
         },


         test() {
            if (this.inputPassWordVisible == true) {
               this.inputPassWordVisible = !this.inputPassWordVisible
               this.showKeyboard = !this.showKeyboard
               this.overlayVisable = !this.overlayVisable
            }
         },

         showInputPayVisible() {
            this.inputPassWordVisible = !this.inputPassWordVisible
            this.showKeyboard = !this.showKeyboard
            this.overlayVisable = !this.overlayVisable
         },


         /**
          * 点取消支付 跳转到订单页面
          */

         onCancel() {
            Dialog.confirm({
                  title: '提示',
                  message: '确认取消支付吗？',
               })
               .then(() => {
                  this.clearSession();
                  // this.order.remainingTime = this.time;
                  // this.order.status = 2
                  // request.post(this.url.order,
                  //    this.order
                  // )
                  sessionStorage.setItem('curActive', 1);
                  this.$router.push("/manager/order")
               })
               .catch(() => {

               });

         },

         /**
          * 校验密码
          */
         checkPassword() {
            if (this.password.length == 0) {
               return;
            } else if (this.password.length > 0 && this.password.length < 6) {
               Toast("输入密码不够6位")
               return;
            } else {
               if (this.customerInfo.payPassword == this.password) {
                  // 钱不够 订单状态 设为 2. 未支付
                  if (this.customerInfo.balance < this.order.totalMoney) {
                     Dialog.confirm({
                           title: '余额不足',
                           message: '请点击确定，前往充值！',
                        })
                        .then(() => {
                           this.clearSession()
                           this.$router.push('/manager/mine')
                        })
                        .catch(() => {
                           // on cancel
                        });
                  } else {
                     this.pay()
                  }
               } else {
                  this.overlayVisable = !this.overlayVisable
                  Toast("密码错误！")
               }
            }
            this.password = ''
            this.inputPassWordVisible = false
            this.showKeyboard = false
         },

         /**
          * 密码 正确支付  清空购物车 和 商品展示的 session 扣减余额  跳到订单界面
          */
         pay() {

            this.clearSession();

            // 5. 剩余支付时间清0
            this.order.remainingTime = 0;

            // 6. 修改订单状态
            this.order.status = 1;

            //7.调后台接口扣减余额
            this.customerInfo.balance -= this.order.totalMoney
            this.updateCustomerInfo({
               customerInfoTemp: this.customerInfo
            })

         //   console.log(this.order)


            // 8 更新订单状态
            this.upDateStatusById(this.order);
            //8.插入订单
            // request.post(this.url.order,
            //    this.order
            // ).then(
            //    res => {
            //       if (res.data.code == "200") {
            //          Dialog.alert({
            //             title: '提示',
            //             message: '支付成功',
            //          }).then(() => {
            //             sessionStorage.setItem('curActive', 1);
            //             this.$router.push("/manager/order")
            //          });
            //       }
            //    }
            // )

         },

         /**
          * 更新订单状态
          * @param {} order 
          */
         upDateStatusById(order) {

            request.post("/schoolOrder/app/order/updateOrderById", {
               id: order.id,
               status: order.status,
               foodList: order.foodList,
               num: order.num,
               shopId: order.shopId,
            }).then(
               res => {
                  if (res.data.code == "200") {
                     Dialog.alert({
                        title: '提示',
                        message: '支付成功',
                     }).then(() => {
                        sessionStorage.setItem('curActive', 1);
                        this.$router.push("/manager/order")
                     });
                  }
               }
            )
         },


         clearSession() {
            var key1 = this.customerInfo.username + 'order'; //session 中的 order
            var key2 = this.order.shopName + this.customerInfo.username + 'goodList'; //session 中的 goodList
            var key3 = this.order.shopName + this.customerInfo.username + 'shopCart'; //session 中的 shopCarts
            var key4 = this.customerInfo.username + this.order.shopName + "waitPay"; // session中的 订单是否支付
            // 1. 清空session中的购物车
            sessionStorage.removeItem(key1);
            // 2. 清空session中的商品展示
            sessionStorage.removeItem(key2);
            // 3.清除session中的订单
            sessionStorage.removeItem(key3);
            // 4.清楚订单支付标志
            sessionStorage.removeItem(key4);
         },

         /**
          * 动作面板返回的事件
          */
         onSelectPayType(item) {

            this.payType = item.name;
            this.order.payType = item.name;
            this.showPayTypeVisable = false;
         },


         async getAddressList() {

            await request.get('/schoolOrder/app/getCustomerByToken?token=' + localStorage.getItem('token'))
               .then(
                  res => {

                     this.customerInfo = res.data.data
                     //    console.log(this.customerInfo)
                  }
               )

            await request.get('/schoolOrder/app/list', {
               params: {
                  customerId: this.customerInfo.id
               }
            }).then(
               res => {
                  this.addressList = res.data.result.records
                  //  console.log(this.addressList)
                  this.mySetData();
               }
            )
         },


         mySetData() {
            if (sessionStorage.getItem(this.customerInfo.username + "order")) {
               this.order = JSON.parse(sessionStorage.getItem(this.customerInfo.username + "order"))
               this.time = this.order.remainingTime
               this.order.totalMoney *= 1.0
            } else {
               Dialog.alert({
                  message: '请选择商品！！！',
               }).then(() => {

               })
               this.$router.push("/manager/home");
            }

            for (var item of this.addressList) {
               var address = {
                  name: item.address,
                  subname: item.name + " " + item.tel,
                  address: item.address,
                  customerName: item.name,
                  tel: item.tel
               }
               if (item.isDefault == 1) {
                  this.selectedAddress = address
                  this.order.name = item.name;
                  this.order.tel = item.tel;
                  this.order.customerId = this.customerInfo.id;
               }
               this.actions.push(address)
            }
            if (sessionStorage.getItem(this.customerInfo.username + this.order.shopName + "waitPay")) {
               this.payVisable = false;
            }
            this.overlayVisable = false;
         }

      },
      mounted() {
         this.getAddressList();
         this.timer = window.setInterval(() => {
            if (this.payVisable == false) {
               this.time -= 1000
               //  this.order.remainingTime = this.time
               // sessionStorage.setItem(this.customerInfo.username+"order",JSON.stringify(order));
            }
         }, 1000)

      },
      beforeDestroy() {
         clearInterval(this.timer)
         this.timer = null
      },
   }
</script>
<style>
   #OrderConfirm {
      width: 100%;
      height: 100%;
      background-color: rgba(200, 200, 200, 0.216);
      box-sizing: border-box;
      overflow: hidden;
   }

   .wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

   }

   #loading {
      color: grey;
   }

   #banner {
      background-color: gold;
      border-bottom-left-radius: 5px;
      border-bottom-right-radius: 5px;
   }

   #box01 {
      width: 88%;
      /* height: 200px; */
      margin-left: 2%;
      margin-top: 1%;
      background-color: white;
      border-radius: 10px;
      padding: 15px;
   }

   #box02 {
      width: 95%;
      margin-left: 2%;
      margin-top: 2%;
      background-color: white;
      border-radius: 10px;
   }

   #food {
      /* background-color: aqua; */
      width: 96%;
      height: 150px;
      overflow-y: auto;
      margin-left: 15px;
   }

   .myButton {
      background-color: gold;
      border: 0;
      width: 95%;
      box-sizing: border-box;
      margin-left: 2%;
      margin-top: 10px;
   }

   .van-image__img {
      width: 70%;
      height: 70%;
   }

   .inputPassword {
      padding: 5%;
      width: 250px;
      height: 150px;
   }

   /* .van-key--blue {
      background-color: gold;
   } */
</style>